<template>
  <div class="choose-model">
    <ArrowContainer head-text="选择模式">
      <div slot="content">
        <div class="model-type">
          <el-radio-group v-model="modelType" @change="changeModelType">
            <el-radio :label="1">随机选择</el-radio>
            <el-radio :label="2">手动选择</el-radio>
          </el-radio-group>
        </div>
        <div class="random-model" style="width: 230px;padding: 10px 0" v-show="modelType == '1'">
          <el-input v-model="randomModelCount" style="text-align: center;">
            <template slot="prepend">设备数量</template>
            <template slot="append">
              <el-button style="color: #bf0a0a;" @click="randomModel" :loading="randLoading">确定</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </ArrowContainer>
    <ArrowContainer head-text="选择测试设备" v-show="modelType =='2'">
      <div slot="content" class="choose-model-list">
        <Model
          v-for="(item, index) in deviceList"
          :key="index"
          :device-data="item"
          @selectChange="selectChange"
        ></Model>
      </div>
    </ArrowContainer>
    <ArrowContainer head-text="建议">
      <div slot="content">
        <p>
          每次测试，尽量选择更多的手机，可以有效避免因手机性能、电量、网络以及其他原因导致的无效运行
          <br>并且覆盖到多种手机厂商与android系统版本，分辨率等，可以让测试结果更有信服力。
          <br>目前OPPO,VIVO,小米手机在安装时失败概率较高，不建议使用。
          <br>注意：选择手机前，请先到远程真机页面，检查一下手机是否锁屏。如果锁屏，请先手动解锁，以免测试任务卡在锁屏页
        </p>
      </div>
    </ArrowContainer>
  </div>
</template>
<script>
import ArrowContainer from "../common/ArrowContainer";
import Model from "../common/Model";
import tcdevicesApi from "@/api/tcdevices.js";
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
  name: "ChooseModel",
  data() {
    return {
      deviceList: [],
      timer: '',
      modelType: 1,
      randomModelCount: 0,
      randLoading: false
    };
  },
  components: {
    ArrowContainer,
    Model
  },
  props: [
    'current'
  ],
  watch: {
    'current' (val) {
      if (val) {
        this.intervalList()
      } else {
        if (this.timer) {
          clearInterval(this.timer)
          this.timer = ''
        }
      }
    }
  },
  methods: {
    ...mapMutations("autotest", ["setSelectPhoneList"]),
    compare(name, minor) {
      return function(o, p) {
        var aaa, bbb;
        if (o && p && typeof o === "object" && typeof p === "object") {
          aaa = o[name];
          bbb = p[name];
          if (aaa === bbb) {
            return typeof minor === "function" ? minor(o, p) : 0;
          }
          if (typeof aaa === typeof bbb) {
            return bbb - aaa > 0 ? -1 : 1;
          }
          return typeof bbb < typeof aaa ? -1 : 1;
        } else {
        }
      };
    },
    // 随机选取设备
    changeModelType(val) {
      if (val == 1) {
          this.$emit("selectModel", [])
          this.setSelectPhoneList([])
      } else if (val == 2) {
          this.selectChange()
      }
    },
    randomModel() {
      this.randLoading = true
      tcdevicesApi.getTcDevices().then(
        res => {
          var devices = res.data.data
          devices = devices.filter(item => {
            item.isSelected = false;
            return item.hasOwnProperty("abi") && item.present && !item.using && item.ready && (item.owner == null);
          })

          if (this.randomModelCount <= 0) {
            this.randLoading = false
            this.$message({
              message: '请选择设备数量',
              type: 'warning'
            })
            return 
          }

          if (devices.length < this.randomModelCount) {
            this.randLoading = false
            this.$message({
              message: '设备数量不足 ' + this.randomModelCount + '台',
              type: 'warning'
            })
            return 
          }

          function getRandomArrayElements(arr, count) {
              var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index
              while (i-- > min) {
                  index = Math.floor((i + 1) * Math.random())
                  temp = shuffled[index]
                  shuffled[index] = shuffled[i]
                  shuffled[i] = temp
              }
              return shuffled.slice(min)
          }

          devices = getRandomArrayElements(this.deviceList, this.randomModelCount)

          console.log('random devices ', devices)
          this.$emit("selectModel", devices)
          this.setSelectPhoneList(devices)

          this.randLoading = false
        }
      )
    },
    // 获取云真机列表
    getDeviceList() {
      tcdevicesApi.getTcDevices().then(
        res => {
          this.deviceList = res.data.data;
          this.deviceList.forEach(item => {
            item.isSelected = false;
            // 暂时使用默认图片
            item.pic = `${process.env.STF_URL}/static/app/devices/icon/x120/_default.jpg`
          });
          this.deviceList = this.deviceList.filter(item => {
            return item.hasOwnProperty("abi") && item.present && !item.using && item.ready && (item.owner == null);
          });
          this.deviceList.sort(
            this.compare("present", this.compare("use_time"))
          );
          this.deviceList = this.deviceList.reverse();
          console.log(this.deviceList);
        },
        error => {
          this.$message.error(`获取设备列表失败: ${error.message}`);
        }
      );
    },
    // model切换选中
    selectChange() {
      let selectedList = this.deviceList.filter(item => {
        return item.isSelected;
      });
      this.$emit("selectModel", selectedList);
      this.setSelectPhoneList(selectedList);
    },
    // 轮询手机列表
    intervalList() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = ''
      }
      this.timer = setInterval(() => {
        this.getDeviceList()
      }, 3000)
    }
  },
  created() {
    this.getDeviceList();
    if (this.current) {
      this.intervalList()
    }
  },
  beforeDestroy() {
    this.setSelectPhoneList([]);
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = ''
    }
  }
};
</script>
<style scoped lang="scss">
.choose-model {
  .choose-model-list {
    display: flex;
    justify-content: start;
    flex-wrap: wrap;
  }
}
</style>